import { onMounted, reactive } from "vue";

export const act = reactive({


  run: true,
  speed: 55.2,
  WebSockeetServer: false,
  micrologix1400: {
    MicrologixT: {
      b3_17: false,
      n7_2_3: false,
      M_f8_0: 0,
      M_f8_1: 0,
      M_N7_0: 0,
      M_N7_1: 0,
      M_F8_8: 0,
      M_F8_9: 0,
    }
  },
  PD_101: {
    commnaction_status: false,
    Gen: {
      HD101_Pop_CtrlSPD_AO: 0,
      HD101_Pop_HNMode_AI: 0,
      HD101_Pop_ModeLocal_DI: false,
      HD101_Pop_ModeRemote_DI: false,
      HD101_Pop_ModeLOCK_DI: false,
      HD101_Pop_CtrlRESET_DO: false,
      HD101_Pop_CtrlRUN_DO: false,
      HD101_Pop_CtrlSTOP_DO: false,
      HD101_Pop_CtrlUNLOCK_DO: false,
      HD101_HNWarning_AI: false,
      HD104_SPD_AI: 0,
      HD105_SPD_AI: 0,
    },
    Belt101_Gen: {
      HD101_Pop_RUN_DI: false,
      HD101_Pop_SPD_AI: 0,
      HD101_Alarm_DI: false,
    },
    Belt104_105_Gen: {
      HD104_SPD_AI: 0,
      HD105_SPD_AI: 0,
    },

  }
});
let ws;
let intervalId;
const messageQueue: any[] = [];
//websocket  topic=plc_logix::topic
export function createWebSocket(topic) {
  if (ws) {
    ws.close
  }
  ws = new WebSocket("ws://192.168.31.130:5000/ws/");


  ws.onopen = () => {
    console.log("Connected to WebSocket server");
    act.WebSockeetServer = true;
    const sendtopic = { topic: topic }; //device::topic
    const sort = { action: "read" };

    intervalId = setInterval(() => {
      const msg = { ...sort, ...sendtopic };
      console.log(msg);
      enqueueMessage(msg);
    }, 3000);

    // 启动队列处理逻辑
    processMessageQueue();
  };

  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      //  console.log("Received data:", data);
      // 判断是否为数组
      if (Array.isArray(data)) {
        ProcessDataArray(data); // 如果是数组，调用 ProcessDataArray
      } else {
        ProcessDataNew(data); // 否则调用 ProcessDataNew
      }
    } catch (error) {
      console.error("Error parsing message:", error);
    }
  };

  ws.onerror = (error) => {
    console.error("WebSocket error:", error);
    act.WebSockeetServer = false;
    clearInterval(intervalId);
  };

  ws.onclose = () => {
    console.log("WebSocket connection closed, retrying...");
    act.WebSockeetServer = false;
    clearInterval(intervalId);
    setTimeout(createWebSocket, 5000); // 5秒后重新连接
  };

  // 处理队列中的消息
  function processMessageQueue() {
    setInterval(() => {
      if (ws && ws.readyState === WebSocket.OPEN && messageQueue.length > 0) {
        const message = messageQueue.shift(); // 取出队列中的第一个消息
        ws.send(JSON.stringify(message));
        // console.log("Sent message from queue:", message);
      } else if (messageQueue.length > 0) {
        console.log("WebSocket not ready, waiting to send message...");
      }
    }, 100); // 每 100ms 检查一次队列
  }

  function ProcessDataArray(datas) {
    console.log(datas);
    datas.forEach((element) => {
      ProcessDataNew(element);
    });
  }
  function normalizeValue(value: any): any {
    if (value === 'True' || value === 'true') return true;
    if (value === 'False' || value === 'false') return false;
    if (!isNaN(value) && typeof value === 'string') {
      return Number(value);
    }
    return value;
  }
  function ProcessDataNew(data) {
    // 自动识别使用 "::" 或 "." 拆分路径
    const path = data.Name.includes("::")
      ? data.Name.split("::")
      : data.Name.split(".");
    const normalizedValue = normalizeValue(data.Value);
    setValueIfExists(act, path, normalizedValue);
  }
  function setValueIfExists(obj: any, path: string[], value: any) {
    let current = obj;
    for (let i = 0; i < path.length - 1; i++) {
      if (!(path[i] in current)) {
        console.warn(`路径错误: 找不到属性 '${path.slice(0, i + 1).join('.')}'`);
        return; // 找不到对应路径，终止赋值
      }
      current = current[path[i]];
    }
    const lastKey = path[path.length - 1];
    if (!(lastKey in current)) {
      console.warn(`路径错误: 找不到属性 '${path.join('.')}'`);
      return;
    }
    // 找到了完整路径，赋值
    current[lastKey] = value;
  }
}
// 将消息加入队列
function enqueueMessage(message) {
  messageQueue.push(message);
}


export function sendDataFromButton(tag: string, value: string | number | boolean) {
  console.log("-------------------");

  // 解析 tag: "act.AAA.BBB.CCC"
  const parts = tag.split(".");
  if (parts.length !== 4 || parts[0] !== "act") {
    console.error("Invalid tag format. Expected format: act.AAA.BBB.CCC");
    return;
  }
  const [_, AAA, BBB, CCC] = parts;
  const formattedTag = `ns=1;s=${AAA}::${BBB}::${CCC}`;

  // 构建写入数据（不再需要 data_type）
  const wvalue = [{
    tag: formattedTag,
    value: value.toString()
  }];

  const btnMsg = {
    action: "write",
    data: wvalue
  };

  console.log(btnMsg);
  enqueueMessage(btnMsg);
  console.log("Button: Added message to queue");
}
